<template>
  <div>
    <h-drawer
      v-model="visible"
      :width="1200"
      unit="px"
      :loading="
        getWarehouseLoading ||
        getSparePartInfoBeforeCheckLoading ||
        orderSparePartCheckLoading ||
        getSparePartListBeforeCheckLoading
      "
      @close="hideDrawer"
    >
      <template #title>
        <div class="drawer_title_container">
          <span>{{ props.applyType === 'backup-machine' ? '审核备用机' : '审核配件' }}</span>
          <h-status type="warning" :height="20">待审核</h-status>
        </div>
      </template>
      <div class="body">
        <div class="form">
          <div class="title">基本信息</div>
          <div class="info_list">
            <div class="info_item">
              <div class="label">
                {{ props.applyType === 'backup-machine' ? '备用机' : '配件' }}编号:
              </div>
              <div class="value">{{ sparePartInfoBeforeCheck.code }}</div>
            </div>
            <div class="info_item">
              <div class="label">工单单号:</div>
              <div class="value">{{ sparePartInfoBeforeCheck.workNo }}</div>
            </div>
            <template v-if="props.applyType === 'spare-part'">
              <div class="info_item">
                <div class="label">申请类型:</div>
                <div class="value">{{ options6[sparePartInfoBeforeCheck.type - 1].name }}</div>
              </div>
              <div v-if="sparePartInfoBeforeCheck.type === 2" class="info_item">
                <div class="label">部门配件类型:</div>
                <div class="value">{{
                  sparePartInfoBeforeCheck.networkSpareType === 1 ? '公司配件' : '外部配件'
                }}</div>
              </div>
            </template>
          </div>
          <div class="content">
            <el-form label-position="top">
              <div v-if="props.applyType === 'spare-part'" class="warehouse_back_container">
                <!-- 收货地址类型 -->
                <el-form-item label="收货地址类型" class="address_type">
                  <el-select
                    v-model="orderSparePartCheckForm.receiptAddrType"
                    clearable
                    placeholder="收货地址类型"
                    @change="changeAddrType"
                  >
                    <el-option label="工单客户" :value="1" />
                    <el-option label="网点" :value="2" />
                  </el-select>
                </el-form-item>

                <!-- 旧件处理方式 -->
                <el-form-item label="旧件处理方式" class="old_handle_method">
                  <el-select
                    v-model="orderSparePartCheckForm.oldCopeWay"
                    placeholder="旧件处理方式"
                    :disabled="isDisableCheckStatusSelect || props.applyType === 'backup-machine'"
                    @change="changeoldCopeWay"
                  >
                    <el-option label="废弃" :value="1" />
                    <el-option label="旧件退回" :value="2" />
                  </el-select>
                </el-form-item>

                <el-form-item v-if="orderSparePartCheckForm.oldCopeWay === 2" label="退回仓库">
                  <el-select
                    v-model="orderSparePartCheckForm.storeId"
                    :loading="getWarehouseEntryOptionListLoading"
                    placeholder="请选择仓库"
                    filterable
                    :filter-method="handleGetWarehouseOptionList"
                    @change="changeoldCopeWay(1)"
                  >
                    <template #header>
                      <div class="select_header">
                        <el-input
                          v-model.trim="getReturnWareHouseOptionsParam.name"
                          placeholder="请输入关键字"
                          @keyup.enter="getReturnWareHouseOptionsFn"
                        />
                        <h-plain-button @click="getReturnWareHouseOptionsFn">搜索</h-plain-button>
                      </div>
                    </template>
                    <el-option
                      v-for="item in warehouseEntryOptionList"
                      :key="item.name"
                      :label="item.name"
                      :value="item.id"
                      @click="handleChangeReturnWareHouse(item)"
                    />
                  </el-select>
                  <div v-if="orderSparePartCheckForm.storeId" class="back_warehouse_info_list">
                    <div class="info_item">
                      <div class="label">姓名:</div>
                      <div class="value">{{ orderSparePartCheckForm.oldReceiptName }}</div>
                    </div>
                    <div class="info_item">
                      <div class="label">手机号:</div>
                      <div class="value">{{ orderSparePartCheckForm.oldReceiptPhone }}</div>
                    </div>
                    <div class="info_item">
                      <div class="label">仓库地址:</div>
                      <div class="value">
                        {{
                          orderSparePartCheckForm.oldReceiptProvince +
                          orderSparePartCheckForm.oldReceiptCity +
                          orderSparePartCheckForm.oldReceiptArea +
                          orderSparePartCheckForm.oldReceiptTown +
                          orderSparePartCheckForm.oldReceiptAddress
                        }}
                      </div>
                    </div>
                  </div>
                </el-form-item>

                <el-form-item
                  v-if="
                    isEnableStorePosition(
                      orderSparePartCheckForm.storeId,
                      warehouseEntryOptionList,
                    ) && orderSparePartCheckForm.oldCopeWay === 2
                  "
                  label="退回仓位"
                >
                  <el-select
                    v-model="orderSparePartCheckForm.storePositionId"
                    :disabled="
                      !isEnableStorePosition(
                        orderSparePartCheckForm.storeId,
                        warehouseEntryOptionList,
                      )
                    "
                    :loading="loading"
                    placeholder="请选择退回仓位"
                  >
                    <template #header>
                      <div class="select_header">
                        <el-input
                          v-model.trim="getStorePositionOptionsKeyword"
                          placeholder="请输入关键字"
                          @keyup.enter="getStorePositionOptionsFn(orderSparePartCheckForm.storeId)"
                        />
                        <h-plain-button
                          @click="getStorePositionOptionsFn(orderSparePartCheckForm.storeId)"
                        >
                          搜索
                        </h-plain-button>
                      </div>
                    </template>
                    <el-option
                      v-for="item in sotrePositionOptions"
                      :key="item.name"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </div>

              <div class="personal_phone_container">
                <!-- 收货人姓名 -->
                <el-form-item label="收货人姓名" class="person_name">
                  <el-input
                    v-model.trim="orderSparePartCheckForm.receiptName"
                    clearable
                    placeholder="收货人姓名"
                  />
                </el-form-item>

                <!-- 收货人手机号 -->
                <el-form-item label="收货人手机号" class="phone">
                  <el-input
                    v-model.trim="orderSparePartCheckForm.receiptPhone"
                    :maxlength="11"
                    clearable
                    placeholder="收货人手机号"
                    @input="
                      orderSparePartCheckForm.receiptPhone =
                        orderSparePartCheckForm.receiptPhone.replace(/\D/g, '')
                    "
                  />
                </el-form-item>

                <el-form-item label="审核备注" class="remark">
                  <el-input
                    v-model.trim="orderSparePartCheckForm.remark"
                    clearable
                    maxlength="200"
                    placeholder="填写备注信息"
                    show-word-limit
                    size="small"
                    type="textarea"
                    resize="both"
                  />
                </el-form-item>
              </div>

              <div class="address_container">
                <el-form-item label="收货人地址">
                  <single-address ref="singleAddressInstance" :address="addrs" />
                </el-form-item>
                <el-form-item label="详细地址">
                  <el-input
                    v-model.trim="orderSparePartCheckForm.receiptAddress"
                    :rows="2"
                    clearable
                    maxlength="200"
                    placeholder="收货人详细地址"
                    show-word-limit
                    size="small"
                    type="textarea"
                    resize="both"
                  />
                </el-form-item>
              </div>
            </el-form>
          </div>
        </div>
        <div class="table">
          <el-table :border="true" :data="sparePartList" resizable stripe height="100%">
            <el-table-column fixed="left" label="序号" width="50" type="index" :align="'center'" />

            <!-- 结算类型 -->
            <el-table-column v-if="props.applyType === 'spare-part'" label="结算类型" width="150">
              <template #default="{ row, $index }">
                <el-select
                  v-model="row.type"
                  placeholder="结算类型"
                  @change="handleIncomeOrPayTypeChange($index)"
                >
                  <el-option
                    v-for="item in incomeOrPayTypeOptional"
                    :key="item.value"
                    :value="item.value"
                    :label="item.name"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 配件名称 -->
            <el-table-column
              :label="`${props.applyType === 'backup-machine' ? '备用机' : '配件'}名称`"
              width="240"
            >
              <template #default="{ row }">
                <!-- <el-select
                v-model="scope.row.spareId"
                :loading="getSparePartOptionListLoading"
                placeholder="请选择"
                @change="(id: string) => handleChangePart(id, scope.$index)"
              >
                <template #header>
                  <div class="select_header">
                    <el-input
                      v-model.trim="getSparePartOptionListParam.name"
                      placeholder="请输入关键字"
                      @keyup.enter="getSparePartOptionList(props.workId)"
                    />
                    <h-plain-button @click="getSparePartOptionList(props.workId)">
                      搜索
                    </h-plain-button>
                  </div>
                </template>
                <el-option
                  v-for="item in sparePartOptionList"
                  :key="item.id"
                  :label="`${item.model}`"
                  :value="item.id"
                  @click="handlePartOptionClick(item, scope.$index)"
                />
              </el-select> -->
                <el-input disabled :model-value="row.sparePartName" />
              </template>
            </el-table-column>

            <!-- 规格 -->
            <el-table-column label="规格" width="180">
              <template #default="scope">
                <el-select
                  v-model="scope.row.specId"
                  :loading="getSparePartSpecOptionListLoading"
                  placeholder="请选择"
                  disabled
                  @change="(id: any) => handlePartSpecClick(id, scope.$index)"
                >
                  <template #header>
                    <div class="select_header">
                      <el-input
                        v-model.trim="getPartSpecOptionsKeyword"
                        placeholder="请输入关键字"
                        @keyup.enter="getPartSpecOptionsFn(scope.row.spareId || '', scope.$index)"
                      />
                      <h-plain-button
                        @click="getPartSpecOptionsFn(scope.row.spareId || '', scope.$index)"
                      >
                        搜索
                      </h-plain-button>
                    </div>
                  </template>
                  <el-option
                    v-for="item in scope.row.partSpecOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                    @click="handlePartSpecClick(item, scope.$index)"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 规格编码 -->
            <!-- <el-table-column label="规格编码" width="180" prop="model">
            <template #default="scope">
              <el-input :value="scope.row.checkSpareSpecCode" disabled />
            </template>
          </el-table-column> -->

            <!-- 物料质保状态-->
            <el-table-column label="质保状态" width="150">
              <template #default="{ row, $index }">
                <el-select
                  v-model="row.overinsured"
                  placeholder="质保状态"
                  @change="handleIncomeOrPayTypeChange($index)"
                >
                  <el-option label="保内" :value="false" />
                  <el-option label="保外" :value="true" />
                </el-select>
              </template>
            </el-table-column>

            <template v-if="props.applyType === 'spare-part'">
              <!-- 申请数量 -->
              <el-table-column label="申请数量" width="90">
                <template #default="{ row }">
                  <el-input v-model.trim.number="row.qty" clearable placeholder="数量" />
                </template>
              </el-table-column>

              <!-- 公司承担 -->
              <el-table-column label="公司承担费用单价" width="140">
                <template #default="{ row }">
                  <el-input-number
                    v-model.trim="row.price"
                    style="width: 90px"
                    clearable
                    :controls="false"
                  />
                </template>
              </el-table-column>

              <!-- 客户承担 -->
              <el-table-column label="收取客户费用单价" width="140">
                <template #default="{ row }">
                  <el-input-number
                    v-model.trim="row.customerUndertakePrice"
                    style="width: 90px"
                    clearable
                    :controls="false"
                  />
                </template>
              </el-table-column>

              <!-- 网点承担 -->
              <el-table-column label="支付网点费用单价" width="140">
                <template #default="{ row }">
                  <el-input-number
                    v-model.trim="row.networkUndertakePrice"
                    style="width: 90px"
                    clearable
                    :controls="false"
                  />
                </template>
              </el-table-column>

              <!-- 仓库 -->
              <template v-if="sparePartInfoBeforeCheck.networkSpareType !== 3">
                <el-table-column label="出库仓库" width="180">
                  <template #default="scope">
                    <el-select
                      v-model="scope.row.storeId"
                      :loading="loading"
                      placeholder="请选择"
                      :disabled="
                        sparePartInfoBeforeCheck.type === 2 &&
                        sparePartInfoBeforeCheck.networkSpareType === 1
                      "
                      @change="changeSeleStoreId(scope.row, scope.$index)"
                    >
                      <template #header>
                        <div class="select_header">
                          <el-input
                            v-model.trim="getReturnWareHouseOptionsParam.name"
                            placeholder="请输入关键字"
                            @keyup.enter="getReturnWareHouseOptionsFn"
                          />
                          <HPlainButton @click="getReturnWareHouseOptionsFn">搜索</HPlainButton>
                        </div>
                      </template>
                      <el-option
                        v-for="item in returnWareHouseOptions"
                        :key="item.name"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </template>
                </el-table-column>

                <!-- 仓位 -->
                <el-table-column label="仓位" width="120">
                  <template #default="scope">
                    <el-select
                      v-model="scope.row.storePositionId"
                      :disabled="!isEnableStorePosition(scope.row.storeId, returnWareHouseOptions)"
                      :loading="loading"
                      placeholder="请选择"
                      @change="changeSelestorePositionId(scope.row, scope.$index)"
                    >
                      <template #header>
                        <div class="select_header">
                          <el-input
                            v-model.trim="getTableStorePositionOptionsKeyword"
                            placeholder="请输入关键字"
                            @keyup.enter="
                              getTableStorePositionOptionsFn(scope.row.storeId, scope.$index)
                            "
                          />
                          <h-plain-button
                            @click="getTableStorePositionOptionsFn(scope.row.storeId, scope.$index)"
                          >
                            搜索
                          </h-plain-button>
                        </div>
                      </template>
                      <el-option
                        v-for="item in scope.row.warehousePositionOptionList"
                        :key="item.name"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </template>
                </el-table-column>

                <!-- 即时库存 -->
                <el-table-column label="即时库存" width="180">
                  <template #default="scope">
                    <span>{{ scope.row.systemStock }}</span>
                  </template>
                </el-table-column>
              </template>

              <!-- 备注 -->
              <el-table-column label="备注" max-width="150" min-width="140">
                <template #default="scope">
                  <el-input v-model.trim="scope.row.remark" clearable placeholder="填写备注" />
                </template>
              </el-table-column>

              <!-- 附件 -->
              <el-table-column :width="annexColumnWidth" label="附件(最多上传8个)">
                <template #default="scope">
                  <div class="file_list">
                    <template v-for="(img, index) in scope.row.images" :key="index">
                      <h-image
                        :width="60"
                        :height="37.5"
                        :src="img.image"
                        :initial-index="index"
                        :preview-src-list="scope.row.images.map((item: SparePartFormTableItemImageRow) => item.image)"
                        fit="scale-down"
                        :padding="2"
                        :show-del-btn="!img.id"
                        :mask-btn-gap="3"
                        @del="handleDelFile(scope.$index, index)"
                      />
                    </template>
                    <h-image
                      v-if="scope.row.images.length < 8"
                      :src="uploadPlaceholderImg"
                      :width="60"
                      :height="37.5"
                      :padding="2"
                    >
                      <el-upload
                        :auto-upload="false"
                        :on-change="(file) => handleUploadPicture(file, scope.$index)"
                        :show-file-list="false"
                        accept="image/*"
                        action="#"
                        multiple
                      >
                        <div style="height: 35.5px; line-height: 35.5px">
                          <i
                            class="iconfont icon-img-upload"
                            style="color: #fff; font-size: 24px"
                          ></i>
                        </div>
                      </el-upload>
                    </h-image>
                  </div>
                </template>
              </el-table-column>
            </template>

            <!-- 审核状态 -->
            <el-table-column label="审核" width="120" fixed="right" :align="'center'">
              <template #default="{ row }">
                <el-select
                  v-model="row.status"
                  filterable
                  placeholder="审核"
                  @change="handleSelectCheckStatus"
                >
                  <el-option label="通过" :value="2" />
                  <el-option label="驳回" :value="3" />
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <h-button
          is-modal
          type="primary"
          :disabled="$route.query.isArchive == 'true'"
          @click="onSave"
        >
          审核
        </h-button>
        <h-button is-modal @click="hideDrawer">取消</h-button>
      </template>
    </h-drawer>
    <HModal v-model="dialogVisible" title="查看附件">
      <iframe :src="`${dialogImageUrl}`" style="height: 660px; width: 100%"></iframe>
    </HModal>
  </div>
</template>

<script lang="ts" setup>
  import { nextTick, PropType, ref, toRefs, watch } from 'vue'
  import { sparePageSelect } from '@/api/code'
  import {
    getGoodsStock,
    storeEmpAddressPageSelect,
    storePageSelect,
    storePositionPageSelect,
  } from '@/api/store'
  import { getOrderNetworkAddress, getWorkUserAddress } from '@/api/parts'
  import { orderAnnexUpload } from '@/api/upload'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import { UploadFile, UploadRawFile } from 'element-plus'
  import _ from 'lodash'
  import {
    PartOptions,
    PartSpecOptions,
    ReturnWareHouseOptions,
    StorePositionOptions,
  } from '../../../../../views/order/parts/components/types'
  import uploadPlaceholderImg from '@/assets/image/avatar_upload_default.png'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { useGetNetworkWarehouse } from '@/services/pages/storage/useWarehouse'
  import { useGetWarehouseAndPersonAddressList } from '@/services/pages/storage/useWarehouseOut'
  import { SparePartCheckFormTableItem, SparePartFormTableItemImageRow } from './types'
  import {
    useGetOrderSparePartInfoBeforeCheck,
    useSparePartCheckForm,
    useGetSparePartListByOrderSparePartId,
  } from '@/services/module/order/useSparePart'
  import {
    useGetSparePartOptionList,
    useGetSparePartSpecOptionList,
  } from '@/services/pages/good/useGood'
  import { useGetSnCodeOptionListBySparePartId } from '@/services/module/order/useSparePart'

  const { warehouse, getWarehouseLoading, getWarehouse } = useGetNetworkWarehouse()
  const {
    list: warehouseEntryOptionList,
    getListParam: getWarehouseEntryOptionListParam,
    getListLoading: getWarehouseEntryOptionListLoading,
    getList: getWarehouseEntryOptionList,
  } = useGetWarehouseAndPersonAddressList()
  const {
    sparePartInfoBeforeCheck,
    getSparePartInfoBeforeCheckLoading,
    getSparePartInfoBeforeCheck,
  } = useGetOrderSparePartInfoBeforeCheck()
  const {
    orderSparePartCheckForm,
    orderSparePartCheckLoading,
    orderSparePartCheck,
    resetOrderSparePartCheckForm,
  } = useSparePartCheckForm()
  const {
    sparePartListBeforeCheck,
    getSparePartListBeforeCheckLoading,
    getSparePartListBeforeCheck,
  } = useGetSparePartListByOrderSparePartId()
  const {
    optionList: sparePartOptionList,
    getOptionListParam: getSparePartOptionListParam,
    getOptionListLoading: getSparePartOptionListLoading,
    getSparePartOptionList: getSparePartOptionList,
  } = useGetSparePartOptionList()
  const {
    optionList: sparePartSpecOptionList,
    getOptionListParam: getSparePartSpecOptionListParam,
    getOptionListLoading: getSparePartSpecOptionListLoading,
    getOptionList: getSparePartSpecOptionList,
  } = useGetSparePartSpecOptionList()
  const {
    snCodeOptionList,
    getSnCodeOptionListParam,
    getSnCodeOptionListLoading,
    getSnCodeOptionList,
  } = useGetSnCodeOptionListBySparePartId()

  const props = defineProps({
    partsId: {
      type: String,
      required: true,
    },
    workId: {
      type: String,
      required: true,
    },
    networkId: {
      type: String,
      required: true,
    },
    modalType: {
      type: Number,
      default: () => 1,
    },
    applyType: {
      type: String as PropType<'backup-machine' | 'spare-part'>,
      default: () => 'spare-part',
    },
  })

  const emits = defineEmits<{
    (e: 'update-list'): void
  }>()

  // 弹窗显示状态
  const visible = defineModel('modelValue', { type: Boolean, default: false })

  // 附件列宽
  const annexColumnWidth = ref(130)

  // 设置附件列的宽度
  const setAnnexColumnWidth = () => {
    let maxImageLength = Math.max(...sparePartList.value.map((item) => item.images.length))

    // 在图片数量小于8张时要把上传按钮的宽度计算进去
    if (maxImageLength < 8) {
      maxImageLength += 1
    }

    // 这是为了解决删剩一张图时，列宽会变得很小，导致标题会换行
    if (maxImageLength > 0) {
      annexColumnWidth.value = maxImageLength * 60 + (maxImageLength - 1) * 8 + 24
    }

    if (annexColumnWidth.value < 130) {
      annexColumnWidth.value = 130
    }
  }

  // 收支类型选项
  const incomeOrPayTypeOptional = [
    { name: '公司承担', value: 1 },
    { name: '收取客户', value: 2 },
    { name: '支付网点', value: 3 },
  ]

  /**
   * 获取配件详情
   * @param index
   */
  const getSpareDetail = (index: number) => {
    return sparePartList.value[index]
  }

  /**
   * 收支类型更新事件
   * @param index - 配件索引
   */
  const handleIncomeOrPayTypeChange = (index: number) => {
    const { partSpecOptions, specId, overinsured, type } = sparePartList.value[index]

    // 提取费用项目的金额
    let price = 0
    if (partSpecOptions && sparePartList.value[index].specId) {
      const feeProject = partSpecOptions.find((module) => module.id === specId)
      if (feeProject) {
        price = overinsured ? feeProject.overPrice : feeProject.price
      }
    }

    sparePartList.value[index].customerUndertakePrice = 0
    sparePartList.value[index].price = 0
    sparePartList.value[index].networkUndertakePrice = 0

    switch (type) {
      case 1:
        sparePartList.value[index].price = price
        break
      case 2:
        sparePartList.value[index].customerUndertakePrice = price
        break
      case 3:
        sparePartList.value[index].networkUndertakePrice = price
        break
    }
  }

  const { workId } = toRefs(props)
  const dialogVisible = ref(false)
  const dialogImageUrl = ref(null)

  // 仓库下拉选项
  const returnWareHouseOptions = ref<Array<ReturnWareHouseOptions>>([])

  const loading = ref(false)

  // 申请类型
  const options6 = [
    { name: '公司配件', value: 1 },
    { name: '外部配件', value: 2 },
  ]

  // 物料列表
  const sparePartList = ref<Array<SparePartCheckFormTableItem>>([])

  const singleAddressInstance = ref()
  const addrs = ref({
    // 地址
    province: '',
    city: '',
    area: '',
    town: '',
  })

  // 获取退回仓库下拉选项请求参数
  const getReturnWareHouseOptionsParam = ref({
    limit: 0,
    name: '',
    page: 0,
    id: '',
  })

  // 获取退回仓库下拉选项加载
  const getReturnWareHouseOptionsLoading = ref(false)

  // 获取退回仓库下拉选项方法
  const getReturnWareHouseOptionsFn = async (networkSpareType: 0 | 1 | 2 = 0) => {
    getReturnWareHouseOptionsLoading.value = true
    const res = await storeEmpAddressPageSelect(
      getReturnWareHouseOptionsParam.value,
      networkSpareType,
    )
    if (res.data.success) {
      returnWareHouseOptions.value = res.data.data.rows
    } else {
      HMessageBox.error(res.data.message)
    }
    getReturnWareHouseOptionsLoading.value = false
  }

  /**
   * 退回仓库下拉选项点击事件
   * @param {object} item - 人员、地址、仓库信息
   */
  const handleChangeReturnWareHouse = (item: ReturnWareHouseOptions) => {
    orderSparePartCheckForm.value.oldReceiptName = item.userName
    orderSparePartCheckForm.value.oldReceiptPhone = item.phone
    orderSparePartCheckForm.value.oldReceiptAddress = item.address
    orderSparePartCheckForm.value.oldReceiptProvince = item.province
    orderSparePartCheckForm.value.oldReceiptCity = item.city
    orderSparePartCheckForm.value.oldReceiptArea = item.area
    orderSparePartCheckForm.value.oldReceiptTown = item.town
    orderSparePartCheckForm.value.storePositionId = ''
    sotrePositionOptions.value = []
    if (isEnableStorePosition(item.id, returnWareHouseOptions.value)) {
      getStorePositionOptionsFn(item.id)
    }
  }

  // 获取仓位下拉选项请求关键字
  const getStorePositionOptionsKeyword = ref('')

  // 仓位下拉选项
  const sotrePositionOptions = ref<Array<StorePositionOptions>>([])

  /**
   * 获取仓位下拉选项方法
   * @param {string} query - 关键字
   * @param {string} id - 仓库id
   */
  const getStorePositionOptionsFn = async (id: string) => {
    if (id) {
      const data = {
        limit: 0,
        page: 0,
        name: getStorePositionOptionsKeyword.value,
      }
      const res = await storePositionPageSelect(data, id)
      sotrePositionOptions.value = res.data.data.rows
    }
  }

  // 获取表格的仓位下拉选项关键字
  const getTableStorePositionOptionsKeyword = ref('')

  /**
   * 获取表格的仓位下拉选项方法
   * @param {string} id - 仓库id
   * @param {number} index - 操作的表格行的索引
   */
  const getTableStorePositionOptionsFn = async (id: string, index: number) => {
    const param = {
      name: getTableStorePositionOptionsKeyword.value,
      limit: 0,
      page: 0,
    }
    const res = await storePositionPageSelect(param, id)
    sparePartList.value[index].warehousePositionOptionList = res.data.data.rows
  }

  //仓库下拉变化
  const changeSeleStoreId = (row: (typeof sparePartList.value)[0], index: number) => {
    row.storePositionId = ''

    // 判断是否启用仓位
    if (isEnableStorePosition(row.storeId, returnWareHouseOptions.value)) {
      getTableStorePositionOptionsFn(row.storeId, index)
    } else {
      changeSelestorePositionId(row, index)
    }
  }

  // 仓位下拉变化
  const changeSelestorePositionId = (row: (typeof sparePartList.value)[0], index: number) => {
    if (row.spareId && row.specId && row.storeId) {
      let data: {
        goodsId: string
        goodsSpecId: string
        storeId: string
        storePositionId: string
        type: 1 | 2
      } = {
        goodsId: row.spareId, //商品ID
        goodsSpecId: row.specId, //商品规格ID
        storeId: row.storeId, //仓库ID
        storePositionId: row.storePositionId, //仓库仓位ID，当仓库启用仓位时，此字段必传
        type: 2, //商品类型：1-成品，2-配件
      }
      sparePartList.value[index].systemStock = 0
      if (!isEnableStorePosition(row.storeId, returnWareHouseOptions.value)) {
        data.storePositionId = row.storePositionId
      }
      getGoodsStock(data).then((res) => {
        if (res) {
          if (res.data.code === 20000) {
            if (res.data.data.row.id && !Number(getSpareDetail(index).price)) {
              sparePartList.value[index].price = res.data.data.row.price
            }
            sparePartList.value[index].systemStock = res.data.data.row.systemStock
          }
        }
      })
    }
  }
  // 判断是否启用仓位
  const isEnableStorePosition = (id: string, storePositions: Array<ReturnWareHouseOptions>) => {
    if (storePositions.length <= 0) {
      return false
    }
    const storePosition = storePositions.find((item) => item.id === id)
    if (!storePosition) {
      return false
    }
    return storePosition.enableStorePosition
  }
  // 地址类型变化
  const changeAddrType = (val: 1 | 2) => {
    switch (val) {
      case 1:
        getWorkUserAddressData()
        break
      case 2:
        getOrderNetworkAddressData()
        break
      default:
        orderSparePartCheckForm.value.receiptName = ''
        orderSparePartCheckForm.value.receiptPhone = ''
        orderSparePartCheckForm.value.receiptAddress = ''
        orderSparePartCheckForm.value.receiptProvince = ''
        orderSparePartCheckForm.value.receiptCity = ''
        orderSparePartCheckForm.value.receiptArea = ''
        orderSparePartCheckForm.value.receiptTown = ''
        addrs.value = {
          province: '',
          city: '',
          area: '',
          town: '',
        }
        singleAddressInstance.value.clearSelectAddr()
        break
    }
  }

  // 旧件处理方式变化
  const changeoldCopeWay = (val: 1 | 2) => {
    switch (val) {
      case 1:
        orderSparePartCheckForm.value.oldReceiptName = ''
        orderSparePartCheckForm.value.oldReceiptPhone = ''
        orderSparePartCheckForm.value.oldReceiptAddress = ''
        orderSparePartCheckForm.value.oldReceiptProvince = ''
        orderSparePartCheckForm.value.oldReceiptCity = ''
        orderSparePartCheckForm.value.oldReceiptArea = ''
        orderSparePartCheckForm.value.oldReceiptTown = ''
        getStorePositionOptionsFn(orderSparePartCheckForm.value.storeId)
        break
      case 2:
        break
    }
  }
  // 获取用户地址
  const getWorkUserAddressData = async () => {
    const res = await getWorkUserAddress(workId.value)
    if (res.data.success) {
      orderSparePartCheckForm.value.userOrNetworkId = res.data.data.row.id
      orderSparePartCheckForm.value.receiptName = res.data.data.row.name
      orderSparePartCheckForm.value.receiptPhone = res.data.data.row.phone
      orderSparePartCheckForm.value.receiptAddress = res.data.data.row.address
      orderSparePartCheckForm.value.receiptProvince = res.data.data.row.province
      orderSparePartCheckForm.value.receiptCity = res.data.data.row.city
      orderSparePartCheckForm.value.receiptArea = res.data.data.row.area
      orderSparePartCheckForm.value.receiptTown = res.data.data.row.town
      addrs.value = {
        province: orderSparePartCheckForm.value.receiptProvince,
        city: orderSparePartCheckForm.value.receiptCity,
        area: orderSparePartCheckForm.value.receiptArea,
        town: orderSparePartCheckForm.value.receiptTown,
      }
    } else {
      HMessageBox.error(res.data.message)
    }
  }
  // 获取网点地址
  const getOrderNetworkAddressData = async () => {
    const res = await getOrderNetworkAddress(workId.value)
    if (res.data.success) {
      orderSparePartCheckForm.value.userOrNetworkId = res.data.data.row.id
      orderSparePartCheckForm.value.receiptName = res.data.data.row.name
      orderSparePartCheckForm.value.receiptPhone = res.data.data.row.phone
      orderSparePartCheckForm.value.receiptAddress = res.data.data.row.address
      orderSparePartCheckForm.value.receiptProvince = res.data.data.row.province
      orderSparePartCheckForm.value.receiptCity = res.data.data.row.city
      orderSparePartCheckForm.value.receiptArea = res.data.data.row.area
      orderSparePartCheckForm.value.receiptTown = res.data.data.row.town
      addrs.value = {
        province: orderSparePartCheckForm.value.receiptProvince,
        city: orderSparePartCheckForm.value.receiptCity,
        area: orderSparePartCheckForm.value.receiptArea,
        town: orderSparePartCheckForm.value.receiptTown,
      }
    } else {
      HMessageBox.error(res.data.message)
    }
  }

  // 获取配件下拉选项请求参数
  // const getPartOptionsKeyword = ref('')

  // 配件下拉选项
  // const partOptions = ref<Array<PartOptions>>([])

  // 获取配件下拉选项加载
  // const getPartOptionsLoading = ref(false)

  /**
   * 获取下拉选项方法
   */
  // const getPartOptionsFn = async () => {
  //   getPartOptionsLoading.value = true
  //   const data = {
  //     limit: 100,
  //     page: 1,
  //     name: getPartOptionsKeyword.value,
  //     departmentId: '',
  //     id: '',
  //   }
  //   const res = await sparePageSelect(data)
  //   partOptions.value = res.data.data.rows
  //   getPartOptionsLoading.value = false
  // }

  /**
   * 配件下拉选项点击事件
   * @param {object} val - 配件信息
   * @param {number} index - 操作的表格行的索引
   */
  // const handlePartOptionClick = (val: PartOptions, index: number) => {
  //   sparePartList.value[index].checkSpareModel = val.model
  // }

  /**
   * 配件选择事件
   * @param sparePart - 配件下拉选项对象
   * @param index - 操作的表格行的索引
   */
  const handleChangePart = (
    sparePart: OrderSparePartAPIResponse.SparePartOption,
    index: number,
  ) => {
    sparePartList.value[index].spareId = sparePart.id
    sparePartList.value[index].sparePartName = sparePart.name
    sparePartList.value[index].sparePartCode = sparePart.code
    if (sparePart.id) {
      getPartSpecOptionsFn(sparePart.id, index)
    }
  }

  // 获取配件规格关键字
  const getPartSpecOptionsKeyword = ref('')

  /**
   * 获取配件规格下拉选项方法
   * @param {string} id - 配件id
   * @param {number} index - 操作的行的索引
   */
  const getPartSpecOptionsFn = async (id: string, index: number) => {
    getSparePartSpecOptionListParam.value = {
      name: '',
      page: 1,
      limit: 100,
    }
    await getSparePartSpecOptionList(id)
    sparePartList.value[index].partSpecOptions = sparePartSpecOptionList.value
  }

  // 仓库下拉数据
  // const getstorePageSelect = async (val: string, index: number) => {
  //   let data = {
  //     limit: 0,
  //     name: val,
  //     page: 0,
  //   }
  //   let networkSpareType = null
  //   if (sparePartInfoBeforeCheck.value?.type == 1) {
  //     networkSpareType = 0
  //   } else {
  //     networkSpareType = sparePartInfoBeforeCheck.value?.networkSpareType
  //   }
  //   const res = await storePageSelect(data, networkSpareType)
  //   if (res) {
  //     sparePartList.value[index].storePageSelect = res.data.data.rows
  //     sparePartList.value[index].storePositionId = null
  //   }
  // }

  /**
   * 保存
   */
  async function onSave() {
    if (orderSparePartCheckForm.value.oldCopeWay == null) {
      orderSparePartCheckForm.value.oldCopeWay = 1
    }

    if (orderSparePartCheckForm.value.oldCopeWay == 2) {
      if (sparePartList.value.some((o) => o.status == 2)) {
        if (!orderSparePartCheckForm.value.storeId) {
          HMessageBox.error('请选择退回的仓库！')
          return
        }
        if (
          !orderSparePartCheckForm.value.storePositionId &&
          orderSparePartCheckForm.value.storeId &&
          isEnableStorePosition(orderSparePartCheckForm.value.storeId, returnWareHouseOptions.value)
        ) {
          HMessageBox.error('请选择退回仓库的仓位！')
          return
        }
      }
    }

    for (let i = 0; i < sparePartList.value.length; i++) {
      let sparePart = sparePartList.value[i]

      const __images: Array<UploadRawFile> = []

      for (let imageIndex = 0; imageIndex < sparePart.images.length; imageIndex++) {
        const file = sparePart.images[imageIndex].file
        if (file) {
          __images.push(file)
        }
      }

      if (__images.length > 0) {
        const res = await orderAnnexUpload(__images)
        sparePartList.value[i].images = res.data.data.rows.map((item) => {
          return { id: '', image: item, file: null, type: 1 }
        })
      }
    }

    sparePartList.value = sparePartList.value.map((sparePart) => {
      delete sparePart.popoverVisible
      delete sparePart.partSpecOptions
      delete sparePart.snCodeOptionList
      delete sparePart.warehouseOptionList
      delete sparePart.warehousePositionOptionList
      delete sparePart.sparePartName
      return sparePart
    })

    orderSparePartCheckForm.value.workSpareMaterials = sparePartList.value

    const res = await orderSparePartCheck()
    if (res && res.code === 20000) {
      HMessage.success('审核完成')
      emits('update-list')
      hideDrawer()
    } else {
      HMessageBox.error('审核失败，请稍后重试')
    }
  }

  /**
   * 配件规格点击事件
   * @param {object} val - 配件规格信息
   * @param {number} index - 操作的表格行的索引
   */
  const handlePartSpecClick = (val: PartSpecOptions, index: number) => {
    // if (Object.prototype.toString.call(val) === '[object Object]') {
    //   sparePartList.value[index].checkSpareSpec = val.name
    //   sparePartList.value[index].checkSpareSpecCode = val.specSkuCode
    // } else {
    //   if (!val) {
    //     sparePartList.value[index].checkSpareSpecCode = ''
    //     sparePartList.value[index].checkSpareSpec = ''
    //   }
    // }

    const price = sparePartList.value[index].overinsured ? val.overPrice : val.price
    sparePartList.value[index].price = 0
    sparePartList.value[index].networkUndertakePrice = 0
    sparePartList.value[index].customerUndertakePrice = 0
    if (sparePartList.value[index].type === 1) {
      sparePartList.value[index].price = price
    }
    if (sparePartList.value[index].type === 2) {
      sparePartList.value[index].customerUndertakePrice = price
    }
    if (sparePartList.value[index].type === 3) {
      sparePartList.value[index].networkUndertakePrice = price
    }
  }

  /**
   * 上传图片事件
   * @param file - 文件
   * @param index - 配件索引
   */
  const handleUploadPicture = (file: UploadFile, index: number) => {
    if (!file.raw) {
      return false
    }

    if (!file.raw.type.includes('image')) {
      HMessageBox.error('只能上传图片类型的文件')
      return
    }

    if (sparePartList.value[index].images.length >= 8) {
      HMessageBox.error('最多上传8个')
      return
    }

    sparePartList.value[index].images.push({
      image: URL.createObjectURL(file.raw),
      file: file.raw,
      id: '',
      type: 1,
    })

    setAnnexColumnWidth()
  }

  /**
   * 弹窗关闭事件
   */
  const hideDrawer = () => {
    visible.value = false
    resetOrderSparePartCheckForm()
  }

  /**
   * 删除文件
   * @param {number} rowIndex - 操作的表格行的索引
   * @param {number} imgIndex - 文件索引
   */
  const handleDelFile = (rowIndex: number, imgIndex: number) => {
    if (sparePartList.value[rowIndex].images[imgIndex].id) {
      HMessageBox.error('禁止删除原本附件')
      return
    }
    const imgs = sparePartList.value[rowIndex].images.splice(imgIndex, 1)
    if (!sparePartList.value[rowIndex].delImageIds) {
      sparePartList.value[rowIndex].delImageIds = [imgs[0].id]
    } else {
      sparePartList.value[rowIndex].delImageIds.push(imgs[0].id)
    }
    setAnnexColumnWidth()
  }

  // 是否禁用旧件处理方式选择器
  const isDisableCheckStatusSelect = ref(false)

  /**
   * 审核状态更新事件
   */
  const handleSelectCheckStatus = () => {
    let isAllReject = true
    sparePartList.value.forEach((item) => {
      if (item.status === 2) {
        isAllReject = false
      }
    })

    isDisableCheckStatusSelect.value = false
    if (isAllReject) {
      isDisableCheckStatusSelect.value = true
      orderSparePartCheckForm.value.oldCopeWay = 1
    }
  }

  /**
   * 入库仓库下拉选项搜索事件
   */
  const handleGetWarehouseOptionList = _.debounce((keyword: string) => {
    if (getWarehouseEntryOptionListParam.value.name !== keyword) {
      getWarehouseEntryOptionListParam.value.name = keyword
      getWarehouseEntryOptionList(0)
    }
  }, 600)

  /**
   * 获取配件审核前的信息
   */
  const getSparePartInfo = async () => {
    await getSparePartInfoBeforeCheck(props.partsId)
    orderSparePartCheckForm.value = {
      id: sparePartInfoBeforeCheck.value.id,
      oldCopeWay: ![1, 2].includes(sparePartInfoBeforeCheck.value.oldCopeWay)
        ? 1
        : sparePartInfoBeforeCheck.value.oldCopeWay,
      oldReceiptAddress: '',
      oldReceiptArea: '',
      oldReceiptCity: '',
      oldReceiptName: '',
      oldReceiptPhone: '',
      oldReceiptProvince: '',
      oldReceiptTown: '',
      receiptAddrType: sparePartInfoBeforeCheck.value.receiptAddrType,
      receiptAddress: sparePartInfoBeforeCheck.value.receiptAddress,
      receiptArea: sparePartInfoBeforeCheck.value.receiptArea,
      receiptCity: sparePartInfoBeforeCheck.value.receiptCity,
      receiptName: sparePartInfoBeforeCheck.value.receiptName,
      receiptPhone: sparePartInfoBeforeCheck.value.receiptPhone,
      receiptProvince: sparePartInfoBeforeCheck.value.receiptProvince,
      receiptTown: sparePartInfoBeforeCheck.value.receiptTown,
      remark: sparePartInfoBeforeCheck.value.reviewRemark,
      storeId: '',
      storePositionId: '',
      userOrNetworkId: '',
      workSpareMaterials: [],
    }

    if (props.applyType === 'backup-machine') {
      orderSparePartCheckForm.value.oldCopeWay = 1
    }

    if (orderSparePartCheckForm.value.receiptAddrType == 1) {
      await getWorkUserAddressData()
    } else if (orderSparePartCheckForm.value.receiptAddrType == 2) {
      await getOrderNetworkAddressData()
    }
  }

  /**
   * 获取列表详情
   * @param {string} id - 配件id
   */
  const getList = async (id: string) => {
    const errorMsg = await getSparePartListBeforeCheck(id)
    if (errorMsg) {
      HMessageBox.error(errorMsg)
      return
    }

    sparePartList.value = sparePartListBeforeCheck.value.map((result) => {
      const sparePart: SparePartCheckFormTableItem = {
        popoverVisible: false,
        warehouseOptionList: [],
        warehousePositionOptionList: [],
        partSpecOptions: [],
        snCodeOptionList: [],
        id: result.id,
        networkUndertakePrice: result.networkUndertakePrice,
        overinsured: result.overinsured,
        price: result.price,
        qty: result.qty,
        remark: result.remark,
        spareId: result.spareId,
        specId: result.specId,
        type: result.type,
        workWarrantyCategoryId: result.workWarrantyCategoryId || '',
        applyDiscountPrice: result.applyDiscountPrice === null ? 0 : result.applyDiscountPrice,
        customerUndertakePrice:
          result.customerUndertakePrice === null ? 0 : result.customerUndertakePrice,
        delImageIds: [],
        discountPrice: result.discountPrice === null ? 0 : result.discountPrice,
        status: 2,
        images: result.images.map((img) => {
          return {
            image: img,
            id: '',
            type: 1,
            file: null,
          }
        }),
        storeId: '',
        storePositionId: '',
        pickingMaterialStatus:
          result.pickingMaterialStatus === null ? 2 : result.pickingMaterialStatus,
        sparePartName: result.spareName,
        sparePartCode: result.spareCode,
      }

      return sparePart
    })
    for (let i = 0; i < sparePartList.value.length; i++) {
      const sparePart = sparePartList.value[i]
      if (sparePart.spareId) {
        await getSparePartOptionList(sparePart.spareId)
        if (sparePartOptionList.value.length > 0) {
          sparePartList.value[i].sparePartName = sparePartOptionList.value[0].name
        }
        await getPartSpecOptionsFn(sparePartList.value[i].spareId, i)
        await getSnCodeOptionList()
        sparePartList.value[i].snCodeOptionList = snCodeOptionList.value
      }
      //   if (sparePartInfoBeforeCheck.value.networkSpareType != 3) {
      //     await getstorePageSelect('', i)
      //   }
    }
    // setAnnexColumnWidth()
  }

  /**
   * 序列号下拉选项筛选事件
   * @param keyword - 搜索关键字
   */
  const handleSnCodeOptionFilter = _.debounce((keyword: string, sparePartIndex: number) => {
    if (getSnCodeOptionListParam.value.code !== keyword) {
      getSnCodeOptionListParam.value.code = keyword
      getSnCodeOptionList().then(() => {
        sparePartList.value[sparePartIndex].snCodeOptionList = snCodeOptionList.value
      })
    }
  }, 500)

  /**
   * 配件编号输入事件
   * @param {string} code - 输入的编号
   * @param {number} sparePartIndex - 配件索引
   */
  const handleSparePartCodeInput = _.debounce(async (code: string, sparePartIndex: number) => {
    const sparePart = sparePartList.value[sparePartIndex]
    if (!sparePart) {
      return false
    }

    if (code) {
      sparePartList.value[sparePartIndex].popoverVisible = true
      getSparePartOptionListParam.value.name = code
      await getSparePartOptionList(props.workId)
    }
  }, 500)

  watch(visible, async (value) => {
    if (value) {
      await getWarehouseEntryOptionList(0)

      if (props.partsId) {
        await getSparePartInfo()
        await getList(props.partsId)
      }

      if (
        sparePartInfoBeforeCheck.value.networkSpareType === 1 &&
        sparePartInfoBeforeCheck.value.type === 2
      ) {
        await getWarehouse(props.networkId)
        await getReturnWareHouseOptionsFn(1)
        // 如果申请类型是外部配件，网点配件类型是网点仓，那么仓库就要拿网点仓的，并且不能改
        if (
          sparePartInfoBeforeCheck.value.networkSpareType === 1 &&
          sparePartInfoBeforeCheck.value.type === 2
        ) {
          sparePartList.value = sparePartList.value.map((item) => {
            item.storeId = warehouse.value.storeId
            return item
          })
        }
      } else {
        await getReturnWareHouseOptionsFn(0)
      }
    }
  })
</script>

<style lang="scss" scoped>
  :deep(.el-input__inner) {
    text-align: left;
  }

  .file_list {
    display: flex;
    column-gap: 8px;

    :deep(.el-upload) {
      width: 40px;
      height: 40px;
    }
  }

  .select_header {
    display: flex;
    gap: 5px;

    :deep(.el-input__wrapper) {
      height: 26px !important;
      font-size: 12px !important;
    }
  }

  .drawer_title_container {
    display: flex;
    align-items: center;
    column-gap: 10px;
  }

  .body {
    height: 100%;
    display: flex;
    flex-direction: column;

    .form {
      .title {
        padding-left: 6px;
        margin-bottom: 12px;
        border-left: 3px solid $primaryColor;
        font-size: 14px;
        font-weight: bold;
      }

      .info_list {
        display: flex;
        padding: 0 0 24px 9px;
        column-gap: 32px;
        flex-wrap: wrap;

        .info_item {
          display: flex;
          column-gap: 5px;

          .label {
            color: #606266;
          }
        }
      }

      .content {
        padding-bottom: 30px;

        :deep(.el-form) {
          display: flex;
          flex-wrap: wrap;
          column-gap: 72px;
          row-gap: 12px;
          padding-left: 9px;

          .warehouse_back_container,
          .personal_phone_container,
          .address_container {
            display: flex;
            flex-direction: column;
            row-gap: 12px;

            .el-form-item {
              width: 250px;

              .el-form-item__label {
                height: 16px;
                line-height: 16px;
                margin-bottom: 3px;
              }

              .el-form-item__content {
                .back_warehouse_info_list {
                  display: flex;
                  column-gap: 12px;
                  width: 320px;
                  flex-wrap: wrap;
                  flex-direction: column;
                  margin-top: 3px;

                  .info_item {
                    display: flex;
                    column-gap: 5px;
                    align-items: flex-start;

                    .label {
                      color: #606266;
                      white-space: nowrap;
                      height: 16px;
                      line-height: 16px;
                      width: 50px;
                      text-align: right;
                    }

                    .value {
                      line-height: 16px;
                    }
                  }
                }

                .el-textarea {
                  width: auto;

                  .el-textarea__inner {
                    min-width: 250px !important;
                    max-width: 550px !important;
                    min-height: 28px !important;
                    max-height: 100px !important;
                    height: 28px;
                  }
                }
              }
            }
          }

          .address_container {
            .el-form-item {
              min-width: 430px;

              .el-form-item__content {
                display: flex;
                column-gap: 5px;
                flex-wrap: nowrap;
                align-items: flex-start;

                .el-cascader {
                  width: 100% !important;
                }

                .el-textarea {
                  width: 100% !important;

                  .el-textarea__inner {
                    width: 100% !important;
                    min-height: 28px !important;
                    max-height: 190px !important;
                    height: 28px;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
</style>
